﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Saxxon.LibDoomSharp
{
    /// <summary>
    /// Abstract class that provides a number of serialization functions for use by derived classes.
    /// </summary>
    abstract public class SerializableBase
    {
        /// <summary>
        /// Instantiate a BinaryReader with the appropriate code page.
        /// </summary>
        protected DataReader GetReader(Stream stream)
        {
            return new DataReader(stream);
        }

        /// <summary>
        /// Instantiate a BinaryWriter with the appropriate code page.
        /// </summary>
        protected DataWriter GetWriter(Stream stream)
        {
            return new DataWriter(stream);
        }

        /// <summary>
        /// When overridden in a derived class, read the object's data from a stream.
        /// </summary>
        abstract protected void Read(Stream stream, int length);

        /// <summary>
        /// Read this object's data from a stream.
        /// </summary>
        virtual public void ReadFrom(Stream stream, int length)
        {
            Read(stream, length);
        }

        /// <summary>
        /// Read this object's data from a file.
        /// </summary>
        virtual public void ReadFromFile(string filename)
        {
            using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                ReadFrom(stream, (int)stream.Length);
            }
        }

        /// <summary>
        /// When overridden in a derived class, write the object's data to a stream.
        /// </summary>
        abstract protected void Write(Stream stream);

        /// <summary>
        /// Write this object's data to a stream.
        /// </summary>
        virtual public void WriteTo(Stream stream)
        {
            Write(stream);
        }

        /// <summary>
        /// Write this object's data to a file.
        /// </summary>
        virtual public void WriteToFile(string filename)
        {
            using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                WriteTo(stream);
                stream.Flush();
            }
        }
    }
}
